import { MessageBox } from "element-ui";
import * as store from "@/store";
import { wsIp } from "../config";
const WSIP = wsIp,
  HeartBeat = 10000,
  MxaTime = 20000,
  Maxima = 5;
let CurrentTime = 0,
  serverTimeoutObj = null,
  timeoutObj = null;
export default class Websocket {
  reconnect = true;
  constructor(url, messageCallback) {
    this.url = !url ? store.state().wsUrl : url;
    // this.messageCallback = messageCallback
    this.global_callback = null;
  }
  init() {
    let vm = this;
    console.log("websocket INIT.....");
    if (typeof WebSocket === "undefined") {
      MessageBox.alert("您的浏览器不支持WebSocket！", "提示", {
        confirmButtonText: "确定",
        callback: action => {}
      });
    } else {
      this.$ws.onopen = () => {
        console.log("websoket连接成功.....");
        this.HeatBeatHandler();
      };
      this.$ws.onmessage = e => {
        // console.log(this.url + '数据:' + e.data)
        this.HeatBeatHandler();
        if (e.data !== "Code200:HeartBeatBack") {
          vm.global_callback(e.data);
        }
      };
      this.$ws.onerror = function() {
        if (this) {
          vm.close();
          console.warn("websocket ERROR 已关闭.....");
        }
      };
      this.$ws.onclose = function() {
        if (this) {
          vm.close();
          console.warn("websocket onclose 已关闭.....");
          vm.reconnect && vm.open();
        }
      };
    }
  }
  open() {
    //初始化websocket
    console.log("websocket初始化中.....");
    this.$ws = new WebSocket(this.wsUrl());
    this.init();
  }
  wsUrl() {
    return "ws://" + WSIP + "/ws/res/" + this.url;
  }
  sendSock(agentData, callback) {
    this.open(); //初始化
    this.global_callback = callback;
    console.log(this.$ws);
    if (this.$ws.readyState === 1) {
      //若是ws开启状态
      //发送消息
    } else if (this.$ws.readyState === 3) {
      CurrentTime++;
      if (CurrentTime >= Maxima) {
        console.log("重新连接失败.....");
        this.close();
      } else {
        setTimeout(() => {
          this.sendSock(agentData, callback);
        }, HeartBeat);
      }
    }
  }
  close() {
    console.log("关闭：" + this.url);
    if (this.$ws.readyState === 3) {
      this.$ws.close();
    }
  }
  HeatBeatHandler() {
    console.log("心跳");
    timeoutObj && clearTimeout(timeoutObj);
    serverTimeoutObj && clearTimeout(serverTimeoutObj);
    timeoutObj = setTimeout(() => {
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      //onmessage拿到返回的心跳就说明连接正常
      this.$ws.send(
        JSON.stringify({
          userNo: this.url,
          serviceName: "res",
          message: "HeartBeat"
        })
      );
      serverTimeoutObj = setTimeout(() => {
        //如果超过一定时间还没重置，说明后端主动断开了,则关闭连接
        this.close();
      }, MxaTime);
    }, HeartBeat);
  }
}
